using Cinemachine;
using NpcFramework;
using System;
using System.Collections.Generic;
using Gameplay.PVE.Entity;
using Gameplay.PVE.Utils;
using Neonagee.LocalPreferences;
using UnityEngine;
using UnityEngine.Rendering.Universal;
using UnityEngine.UI;
using XLua;
using Yoozoo.Core.Common;
using Yoozoo.Framework.Managers;
using Yoozoo.Gameplay.gta;
using Yoozoo.Gta.Common;
using Yoozoo.HRP.Runtime;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Yoozoo.Mars.Got;
using BattleUnit = Gameplay.PVE.Entity.BattleUnit;

namespace Gameplay.PVE
{
    public class PveCameraManager
    {
        private enum ECameraState
        {
            None,
            HangingFocus,
            BattleFocus,
        }
        
        public static PveCameraManager Instance;
        
        public Transform cameraTrans;
        private ECameraState state;
        private BattleUnit followUnit;
        
        public Camera mainCamera;
        public Camera pveMainCamera;
        public Camera rpgMainCamera;
        public Camera uiCamera;
        private HCamera _hCamera;
        
        public CinemachineStateDrivenCamera hangingCamera; //挂机跟随摄像机
        public CinemachineVirtualCamera battleFollowCamera; //战斗跟随摄像机
        public CinemachineVirtualCamera battleFixedCamera;//战斗固定摄像机
        public CinemachineVirtualCamera battleSkillCamera1;
        public CinemachineVirtualCamera BattleSkillCamera2;
        public CinemachineVirtualCamera DeckCamera;

        public CinemachineVirtualCamera battleFixedCamera1;
        
        private CinemachineBasicMultiChannelPerlin battleFixPerlin;
        private CinemachineBasicMultiChannelPerlin battleSkillPerlin;

        private Animation skillAnimation;

        private Dictionary<string, CinemachineVirtualCameraBase> rpgCameras;
        
        
        private enum EPveCameraType
        {
            hanging,
            battleFollow,
            battleFixed,
            battleSkill1,
            battleSkill2,
            deck,
            battleFixed1,
        }

        private Dictionary<EPveCameraType, CinemachineVirtualCameraBase> cameras = new Dictionary<EPveCameraType, CinemachineVirtualCameraBase>();

        public GameObject cameraFocusToken;
        
        public CinemachineCameraOffset hangingOffset;

        public CinemachineBrain brain;

        public CinemachineBrain rpgBrain;

        private Vector2 swipeVector;

        private Vector3 shakeStartCameraPosition;

        private float shakeStartTime;
        private float shakeDuration;
        private float shakeInterval;
        private float shakeCdTime;
        private float shakeRange;

        private GameObject pveCamera;
        private GameObject rpgCamera;
        private HCamera rpgHCamera;

        private CinemachineVirtualCameraBase currentCamera;
        private EPveCameraType currentCameraType;
        private EPveCameraType defaultRpgCameraType = EPveCameraType.battleFixed;


        public void Init()
        {
            shakeStartTime = 0;
           // CameraManager.cameraController.MobileTouchCamera.enabled = false;
           // HCameraManager.DisableCamera(CameraManager.hMainCamera);
            var cameraObj = PveResourceManager.Instance.GetPVECamera();
            cameraTrans = cameraObj.transform;
            cameraObj.transform.SetParent(null);
            cameraObj.SetActive(true);
            UnityEngine.Debug.Log("pveScene:  PveCameraManager..");
            hangingCamera = cameraObj.transform.GetChild(0).GetComponent<CinemachineStateDrivenCamera>();
            pveCamera = cameraObj;

            rpgCamera = PveResourceManager.Instance.GetRpgCamera();
            rpgMainCamera = rpgCamera.GetComponentInChildren<Camera>();
            rpgHCamera = rpgMainCamera.gameObject.GetComponent<HCamera>();
            
            uacdRpg = rpgMainCamera.gameObject.GetComponent<UniversalAdditionalCameraData>();
            
            battleFixedCamera = rpgCamera.transform.GetChild(0).GetComponent<CinemachineVirtualCamera>();
            battleSkillCamera1 = rpgCamera.transform.GetChild(1).GetComponent<CinemachineVirtualCamera>();
            BattleSkillCamera2 = rpgCamera.transform.GetChild(2).GetComponent<CinemachineVirtualCamera>();
            DeckCamera = rpgCamera.transform.GetChild(3).GetComponent<CinemachineVirtualCamera>();
            battleFixedCamera1 = rpgCamera.transform.GetChild(4).GetComponent<CinemachineVirtualCamera>();
            
            rpgCameras = new Dictionary<string, CinemachineVirtualCameraBase>();
            var cvbs = rpgCamera.GetComponentsInChildren<CinemachineVirtualCameraBase>();
            for (int i = 0; i < cvbs.Length; i++)
            {
                rpgCameras[cvbs[i].name] = cvbs[i];
            }
            
            cameras.Clear();
            //cameras.Add(EPveCameraType.hanging,hangingCamera);
            rpgBrain = rpgCamera.GetComponentInChildren<CinemachineBrain>();
            //cameras.Add(EPveCameraType.battleFollow,battleFollowCamera);
            battleFixPerlin = battleFixedCamera.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
            cameras.Add(EPveCameraType.battleFixed,battleFixedCamera);
            cameras.Add(EPveCameraType.battleSkill1,battleSkillCamera1);
            //battleSkillPerlin = battleSkillCamera1.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
            cameras.Add(EPveCameraType.battleSkill2,BattleSkillCamera2);
            cameras.Add(EPveCameraType.deck, DeckCamera);
            cameras.Add(EPveCameraType.battleFixed1,battleFixedCamera1);
            
            //skillAnimation = battleSkillCamera1.GetComponent<Animation>();
            
            hangingOffset = hangingCamera.GetOrAddCompoment<CinemachineCameraOffset>();
            cameraFocusToken = new GameObject("[PveCameraFocusToken]");
            brain = cameraObj.GetComponentInChildren<CinemachineBrain>();
            brain.m_DefaultBlend.m_Style = CinemachineBlendDefinition.Style.Cut;
            brain.enabled = false;
            cameraTrans.position = new Vector3(115,1.5f,83f);
            cameraTrans.localEulerAngles = new Vector3(0,90,0);
            
//            WorldCameraManager.cameraController.enabled = false;
            
            var camera = cameraObj.GetComponentInChildren<Camera>();
            camera.cullingMask &= ~(1 << 5);
            mainCamera = camera;
            pveMainCamera = camera;
            _hCamera = mainCamera.gameObject.GetComponent<HCamera>();
                
            Color color;
            ColorUtility.TryParseHtmlString("#4F647F", out color);
            camera.backgroundColor = color;
            
            
            cameraTrans = camera.transform;
            var fakePerspective = cameraTrans.gameObject.GetComponent<RenderFakePerspective>();
            if (fakePerspective != null)
            {
                fakePerspective.enabled = false;
            }
            Instance = this;
            
            var uiRoot = GameObject.Find("UICamera");
            if (uiRoot == null)
            {
                Debug.LogError("UICamera为空");
                uiCamera = mainCamera;
            }
            else
            {
               uiCamera = uiRoot.GetComponent<Camera>();
            }

            var defaultType = LocalPrefs.GetInt("RpgDefaultCameraType");
            if (defaultType == 0)
            {
                defaultRpgCameraType = EPveCameraType.battleFixed;
            }
            else
            {
                defaultRpgCameraType = EPveCameraType.battleFixed1;
            }
            
            ResidentHandler.Inst.GetFunction("L_RpgManager.SetHangingCamera").Action(cameraObj);
        }

        public void Pause()
        {
            /*foreach (var item in rpgCameras.Values)
            {
                item.m_StandbyUpdate = CinemachineVirtualCameraBase.StandbyUpdateMode.Never;
            }*/
            rpgBrain.enabled = false;
        }

        public void Resume()
        {
            /*foreach (var item in rpgCameras.Values)
            {
                item.m_StandbyUpdate = CinemachineVirtualCameraBase.StandbyUpdateMode.RoundRobin;
            }*/
            rpgBrain.enabled = true;
        }

        public CinemachineVirtualCameraBase GetRpgCameraByName(string name)
        {
            if (rpgCameras.TryGetValue(name, out var camera))
            {
                return camera;
            }
            return null;
        }

        // 启用HCamera，这里延迟启用防止加载界面闪烁
        public void InitHCamera()
        {
            if (_hCamera)
            {
                _hCamera.enabled = true;
            }
        }

        public void ReplaceCamera(GameObject newCamera)
        {
            newCamera.name = "[PveCamera]";
            var newCameraTrans = newCamera.transform;
            newCameraTrans.SetParent(null);
            newCameraTrans.position = cameraTrans.position;
            newCameraTrans.localEulerAngles = cameraTrans.localEulerAngles;
            var camera = newCamera.GetComponent<Camera>();
            camera.fieldOfView = mainCamera.fieldOfView;
            camera.depth = mainCamera.depth;
            camera.nearClipPlane = mainCamera.nearClipPlane;
            camera.farClipPlane = mainCamera.farClipPlane;
            camera.backgroundColor = mainCamera.backgroundColor;
            camera.cullingMask = mainCamera.cullingMask;
            newCamera.AddComponent<CameraShotHelper>();
            GameObject.Destroy(cameraTrans.gameObject);
            cameraTrans = newCamera.transform;
            var audioListener = newCamera.GetComponent<AudioListener>();
            if (audioListener != null)
            {
                audioListener.enabled = false;    
            }
            mainCamera = camera;
            ResidentHandler.Inst.GetFunction("pveManager.onCameraInit").Action(true);
        }
        
        public void StartDrag()
        {
           
        }

        private void SwitchCamera(EPveCameraType type)
        {
            currentCameraType = type;
            if (type != EPveCameraType.hanging)
            {
                SwtichToRpg();
            }
            else
            {
                SwitchToPve();
            }

            if (type != EPveCameraType.battleSkill1)
            {
                ResetSkillCamera();
            }
            
            foreach (var item in cameras)
            {
                if (item.Key == type)
                {
                    item.Value.Priority = 20;
                    if (type == defaultRpgCameraType)
                    {
                        ResetBattleFixFakeCamera(item.Value);
                    }

                    currentCamera = item.Value;
                }
                else
                {
                    item.Value.Priority = 0;
                }
            }
        }

        public void SwitchRpgFixedCamera()
        {
            if (currentCameraType == EPveCameraType.battleFixed)
            {
                defaultRpgCameraType = EPveCameraType.battleFixed1;
                LocalPrefs.SetInt("RpgDefaultCameraType",1);
            }
            else
            {
                defaultRpgCameraType = EPveCameraType.battleFixed;
                LocalPrefs.SetInt("RpgDefaultCameraType",0);
            }
            SwitchCamera(defaultRpgCameraType);
            
            if (currentCamera != null)
            {
                PveFlyTextManager.Instance.RefreshRootForward(currentCamera.transform.forward);
            }
        }
        
        //用于检测是否再屏幕内
        private Camera battleFixedFakeCamera;

        public void ResetBattleFixFakeCamera(CinemachineVirtualCameraBase camera = null)
        {
            if (camera == null)
            {
                camera = battleFixedCamera;
            }
            if (battleFixedFakeCamera == null)
            {
                var obj = new GameObject("BattleFixedCameraFake");

                var cam = obj.AddComponent<Camera>();
                cam.enabled = false;
                battleFixedFakeCamera = cam;
            }

            var trans = battleFixedFakeCamera.transform;
            trans.SetParent(camera.transform);
            trans.localPosition = Vector3.zero;
            trans.localEulerAngles = Vector3.zero;
            trans.localScale = Vector3.one;
            battleFixedFakeCamera.fieldOfView = (camera as CinemachineVirtualCamera).m_Lens.FieldOfView;
            //battleFixedFakeCamera.fieldOfView = camera.
        }
        
        public bool IsInBattleCameraScreen(Vector3 position)
        {
            if (battleFixedFakeCamera == null)
            {
                return true;
            }
            var screenPosition = battleFixedFakeCamera.WorldToScreenPoint(position);
            if (screenPosition.x > Screen.width - 50 || screenPosition.x < 0 || screenPosition.y > Screen.height ||
                screenPosition.y < 0)
            {
                return false;
            }
            return true;
        }

        public Vector3 GetRestrictedPositionByCameraScreen(Vector3 position)
        {
            var screenPosition = battleFixedFakeCamera.WorldToScreenPoint(position);
            var originScreenPosition = screenPosition;
            screenPosition.x = Mathf.Min(Screen.width - 50f, screenPosition.x);
            screenPosition.x = Mathf.Max(0,screenPosition.x);
            screenPosition.y = Mathf.Min(Screen.height, screenPosition.y);
            screenPosition.y = Mathf.Max(0, screenPosition.y);
            if (screenPosition != originScreenPosition)
            {
                var ray = battleFixedFakeCamera.ScreenPointToRay(screenPosition);
                var offset = Mathf.Abs((ray.origin.y - position.y) / ray.direction.y);
                position = ray.origin + offset * ray.direction;
            }
            return position;
        }

        public void OnDrag(Vector2 swipeVector)
        {
            if (!PveManager.Instance.isInPve)
            {
                return;
            }
            swipeVector.x = 1334f / Screen.width * swipeVector.x;
            swipeVector.y = 750f / Screen.height * swipeVector.y;
            this.swipeVector += swipeVector * 0.02f;
            if (this.swipeVector.y > 10)
            {
                this.swipeVector.y = 10;
            }
            else if (this.swipeVector.y < -10)
            {
                this.swipeVector.y = -10;
            }

            if (this.swipeVector.x > 60)
            {
                this.swipeVector.x = 60;
            }
            else if (this.swipeVector.x < -60)
            {
                this.swipeVector.x = -60;
            }

            //hangingCamera.m_XAxis.m_InputAxisValue = this.swipeVector.x;
        }


        public void EndDrag()
        {
            if (!PveManager.Instance.isInPve)
            {
                return;
            }
            this.swipeVector = Vector2.zero;
            //hangingCamera.m_XAxis.m_InputAxisValue = 0;
            //hangingCamera.m_YAxis.m_InputAxisValue = 0;
        }


        public void Shake(float time,float range = 1,float shakeInterval = 0.02f)
        {
            if (PveManager.Instance.isInRpg)
            {
                if (shakeStartTime == 0)
                {
                    shakeStartCameraPosition = cameraFocusToken.transform.position;
                }
                shakeStartTime = TimeManager.logicTime;
                shakeDuration = time;
                shakeRange = range / 20f;
                this.shakeInterval = shakeInterval;
                shakeCdTime = shakeStartTime;
                /*battlePerlin.m_AmplitudeGain = 1;
                battlePerlin.m_FrequencyGain = 1;*/

            }
        }

        public void Update()
        {
            //老震动
            /*if (shakeStartTime != 0)
            {
                if (TimeManager.logicTime - shakeStartTime >= shakeDuration)
                {
                    //battlePerlin.m_AmplitudeGain = 1;
                    //battlePerlin.m_FrequencyGain = 1;
                    cameraFocusToken.transform.position = shakeStartCameraPosition;
                    PveManager.Instance.MoveBgCamera(0,0);
                    shakeStartTime = 0;
                }
                else
                {
                    if (TimeManager.logicTime >= shakeCdTime)
                    {
                        float xOffset = UnityEngine.Random.Range(-1f, 1f) * shakeRange;
                        float yOffset = UnityEngine.Random.Range(-1f, 1f) * shakeRange;
                        Vector3 worldOffset = Quaternion.AngleAxis(cameraTrans.localEulerAngles.y,Vector3.up) * new Vector3(xOffset, yOffset, 0);
                        var newPosition = shakeStartCameraPosition + worldOffset;
                                          
                        //cameraFocusToken.transform.position = shakeStartCameraPosition;
                        var lastFrameDiff = cameraFocusToken.transform.position - shakeStartCameraPosition;
                        var screenPoint = mainCamera.WorldToScreenPoint(newPosition + lastFrameDiff) -
                                          new Vector3(Screen.width / 2, Screen.height / 2,0);
                        cameraFocusToken.transform.position = newPosition;
                        PveManager.Instance.MoveBgCamera(screenPoint.x,screenPoint.y);
                        shakeCdTime = TimeManager.logicTime + shakeInterval;
                    }
                   
                }
            }*/
            //新震动
            if (shakeStartTime != 0)
            {
                if (TimeManager.logicTime - shakeStartTime >= shakeDuration)
                {
                    StopShake();
                }
                else
                {
                    battleFixPerlin.m_AmplitudeGain = shakeRange * 20f;
                    battleFixPerlin.m_FrequencyGain = 1;
                    battleSkillPerlin.m_AmplitudeGain = shakeRange * 20f;
                    battleSkillPerlin.m_FrequencyGain = 1;
                   
                }
            }
        }

        public void StopShake()
        {
            battleFixPerlin.m_AmplitudeGain = 0;
            battleFixPerlin.m_FrequencyGain = 0;
            battleSkillPerlin.m_AmplitudeGain = 0;
            battleSkillPerlin.m_FrequencyGain = 0;
                    
            shakeStartTime = 0;
        }

        public void StartPve(BattleUnit followUnit)
        {
            this.followUnit = followUnit;
            //hangingCamera.gameObject.transform.position = followUnit.Data.position + new Vector3(-5, 5, 0);
            //cameraTrans.transform.position = followUnit.Data.position + new Vector3(-5, 5, 0);
            brain.enabled = true;
            hangingCamera.transform.localPosition = Vector3.zero;
            hangingCamera.Follow = followUnit.gameObject.transform;
            hangingCamera.LookAt = followUnit.gameObject.transform;
            hangingOffset.m_ApplyAfter = CinemachineCore.Stage.Body;
            hangingCamera.m_AnimatedTarget = followUnit.gameObject.GetComponentInChildren<Animator>();

            int childCount = hangingCamera.transform.childCount;
            for (int i = 0; i < childCount; i++)
            {
                var camera = hangingCamera.transform.GetChild(i).GetComponent<CinemachineVirtualCameraBase>();
                camera.Follow = followUnit.gameObject.transform;
                camera.LookAt = followUnit.gameObject.transform;
            }
            /*SwitchCamera(EPveCameraType.hanging);

            battleFixedCamera.Follow = cameraFocusToken.transform;
            battleFixedCamera.LookAt = cameraFocusToken.transform;
            battleFixedCamera1.Follow = cameraFocusToken.transform;
            battleFixedCamera1.LookAt = cameraFocusToken.transform;
            DeckCamera.Follow = cameraFocusToken.transform;
            DeckCamera.LookAt = cameraFocusToken.transform;
            SwitchToPve();*/
        }

        private void SwitchToPve()
        {
            
            rpgCamera.SetActive(false);
            pveCamera.SetActive(true);
            mainCamera = pveMainCamera;
            HCameraManager.EnableCamera(_hCamera);
            cameraTrans = mainCamera.transform;
            ResidentHandler.Inst.GetFunction("pveManager.bindPveCamera").Action(true);
            // 临时切换渲染设置
            var curSetting = QualityHelper.CurrentAdjusterSetting;
            if (curSetting.sceneGraphicLevel > 3)
            {
                Timers.inst.CallLater((o) =>
                {
                    QualityHelper.ApplyShaderLevelAdjuster(curSetting.characterGraphicLevel, 3,
                        curSetting.fxEffectLevel);
                    Timers.inst.CallLater((o2) =>
                    {
                        QualityHelper.ApplyShaderLevelAdjuster(curSetting.characterGraphicLevel, 4,
                            curSetting.fxEffectLevel);
                    });
                });

            }

        }

        private void SwtichToRpg()
        {
            pveCamera.SetActive(false);
            rpgCamera.SetActive(true);
            mainCamera = rpgMainCamera;
            HCameraManager.EnableCamera(rpgHCamera);
            cameraTrans = mainCamera.transform;
            ResidentHandler.Inst.GetFunction("pveManager.bindRpgCamera").Action(true);
        }

        public void SetMainCamera(Camera camera)
        {
            mainCamera = camera;
        }
        
        public void ResetSkillCamera()
        {
            if (battleSkillCamera1 != null)
            {
                battleSkillCamera1.Follow = null;
                battleSkillCamera1.LookAt = null;
            }
        }

        public void SetRpgCameraRenderType(CameraRenderType type)
        {
            HCameraManager.ChangeCameraType(rpgHCamera, type);
        }

        private bool bEnableBalckOut = true;
        public void SetEnableBalckOut(bool bOut)
        {
            bEnableBalckOut = bOut;
        }

        public void RpgToPve(BattleUnit followUnit,Action action)
        {
            SwitchToPve();
            hangingCamera.transform.localPosition = Vector3.zero;
            /*this.followUnit = followUnit;
            hangingCamera.Follow = followUnit.gameObject.transform;
            hangingCamera.LookAt = followUnit.gameObject.transform;*/
            //BlackIn(0.75f);
            brain.m_DefaultBlend.m_Style = CinemachineBlendDefinition.Style.Cut;
            //TimeManager.Instance.DelayCall(750, () =>
            //{
                action?.Invoke();
                SwitchCamera(EPveCameraType.hanging);
                BlackOut(0.75f);
            //});
        }

        private float darkPercent;
        private int fadeState;
        private float fadeTime;
        private float fadeStartTime;

        private Image blackScreenImage;

        private ResLoader loader;
        
        public void BlackIn(float time)
        {
            HCameraManager.BeginBlackFade(1.0f,time);
            
            // fadeState = 1;
            // fadeStartTime = Time.time;
            // fadeTime = time;
            // if (blackScreenImage == null)
            // {
            //     var rootCanvas = GameObject.Find("UIRoot/RootCanvas");
            //     if (rootCanvas != null)
            //     {
            //         var blackScreenImageObj = new GameObject("BlackScreenImage");
            //         blackScreenImageObj.transform.SetParent(rootCanvas.transform);
            //         blackScreenImage = blackScreenImageObj.AddComponent<Image>();
            //         var rect = blackScreenImageObj.GetComponent<RectTransform>();
            //         rect.sizeDelta = new Vector2(Screen.width * 2, Screen.height * 2);
            //         blackScreenImage.color = new Color(0,0,0,0);
            //         blackScreenImage.raycastTarget = false;
            //         if (this.loader == null)
            //             this.loader = ResLoader.Alloc();
            //         
            //         this.loader.Add2Load("Assets/ResourcesAssets/Materials/mat_UI_Overlay.mat",
            //             (success, name, asset) =>
            //             {
            //                 if (success)
            //                 {
            //                     blackScreenImage.material = asset as Material;
            //                 }
            //             }).Load();
            //     }
            // }
        }

        public void BlackOut(float time)
        {
            if (bEnableBalckOut)
            {
                HCameraManager.BeginBlackFade(0, time);
            }
            
            // fadeState = 2;
            // fadeStartTime = Time.time;
            // fadeTime = time;
        }

        public void FixedUpdate()
        {
            if (fadeState != 0)
            {
                var percent = (Time.time - fadeStartTime) / fadeTime;
                if (fadeState == 1)
                {
                    darkPercent = percent;
                }
                else
                {
                    darkPercent = 1 - percent;
                }

                if (percent >= 1)
                {
                    fadeState = 0;
                }
            }
            if (blackScreenImage != null)
            {
                var color = Color.black;
                color.a = darkPercent;
                blackScreenImage.color = color;
            }
        }

        private Vector3 initCameraPos;
        private Vector3 initCameraRotation;
        private float initFOV;
        private Vector3 deckCameraPos = new Vector3(132.9f, 13.3f, 61f);
        private Vector3 deckCameraRotation = new Vector3(31.265f, 1.5f, 0.362f);
        private float deckFOV = 15;

        private UniversalAdditionalCameraData uacd;
        private UniversalAdditionalCameraData uacdRpg;
        
        public void SetPostProcess(bool isOn)
        {
            if (uacd == null)
            {
                uacd = mainCamera.gameObject.GetComponent<UniversalAdditionalCameraData>();
            }

            uacd.renderPostProcessing = isOn;
        }

        public void SetRpgPostProcess(bool isOn)
        {
            if (uacdRpg == null)
            {
                uacdRpg = rpgMainCamera.gameObject.GetComponent<UniversalAdditionalCameraData>();
            }

            uacdRpg.renderPostProcessing = isOn;
        }
        
        public void PveToDeck(Action action)
        {
            SetPostProcess(false);
            rpgBrain.m_DefaultBlend.m_Style = CinemachineBlendDefinition.Style.Cut;
            rpgBrain.m_DefaultBlend.m_Time = 0;
            SwitchCamera(EPveCameraType.deck);
            SetRpgCameraRenderType(CameraRenderType.Overlay);
            cameraFocusToken.transform.position = PveManager.Instance.GetRpgCameraCenterPosition();
            action?.Invoke();
            //SwitchCamera(EPveCameraType.deck);
            rpgBrain.enabled = false;
            initCameraPos = mainCamera.transform.position;
            initCameraRotation = mainCamera.transform.rotation.eulerAngles;
            initFOV = mainCamera.fieldOfView;
            mainCamera.transform.position = deckCameraPos;
            mainCamera.transform.rotation = Quaternion.Euler(deckCameraRotation);
            mainCamera.fieldOfView = deckFOV;
        }

        public void DeckToPve()
        {
            SetPostProcess(true);
            rpgBrain.enabled = true;
            mainCamera.transform.position = initCameraPos;
            mainCamera.transform.rotation = Quaternion.Euler(initCameraRotation);
            mainCamera.fieldOfView = initFOV;
        }

        public void RpgToRpg(Action action)
        {
            Debug.Log("进入rpg黑屏开始");
            BlackIn(0.5f);
            TimeManager.Instance.DelayCall(600, () =>
            {
                Debug.Log("进入rpg黑屏准备结束");
                cameraFocusToken.transform.position = PveManager.Instance.GetRpgCameraCenterPosition();
                action?.Invoke();
                SetRpgCameraRenderType(CameraRenderType.Base);
                rpgBrain.m_DefaultBlend.m_Style = CinemachineBlendDefinition.Style.Cut;
                rpgBrain.m_DefaultBlend.m_Time = 0;
                SwitchCamera(defaultRpgCameraType);
                PveTaskManager.Instance.AddTask(() =>
                {
                    Debug.Log("进入rpg黑屏结束");
                    BlackOut(0.5f);
                });
            },true);
        }

        public void DeckToRpg()
        {
            if (PveGlobalVlues.RpgFightUseTextureBg)
            {
                rpgBrain.m_DefaultBlend.m_Style = CinemachineBlendDefinition.Style.Cut;
                rpgBrain.m_DefaultBlend.m_Time = 0;
            }
            else
            {
                rpgBrain.m_DefaultBlend.m_Style = CinemachineBlendDefinition.Style.EaseInOut;
                rpgBrain.m_DefaultBlend.m_Time = 1.7f;
            }
            SwitchCamera(defaultRpgCameraType);
        }

        public void PveToRpgDeck()
        {
            cameraFocusToken.transform.position = PveManager.Instance.GetRpgCameraCenterPosition();
            rpgBrain.m_DefaultBlend.m_Style = CinemachineBlendDefinition.Style.Cut;
            rpgBrain.m_DefaultBlend.m_Time = 0;
            SwitchCamera(EPveCameraType.deck);
            SetRpgCameraRenderType(CameraRenderType.Base);
        }
        
        public void PveToRpg()
        {
            SwitchCamera(EPveCameraType.battleFollow);
            rpgBrain.m_DefaultBlend.m_Style = CinemachineBlendDefinition.Style.EaseInOut;
        }

        public void RpgStart()
        {
            SwitchCamera(defaultRpgCameraType);
            cameraFocusToken.transform.position = PveManager.Instance.GetRpgCameraCenterPosition();
            hangingCamera.LookAt = null;
            hangingCamera.Follow = null;
        }

        public void SkillStartPrepare(Transform focus,string animName)
        {
            rpgBrain.m_DefaultBlend.m_Style = CinemachineBlendDefinition.Style.Cut;
            rpgBrain.m_DefaultBlend.m_Time = 0;
            //SwitchCamera(EPveCameraType.battleSkill1);
            if (PveGlobalVlues.EnableSkillCamera)
            {
                Debug.Log("[SkillDisplay] "+animName);
                skillAnimation.Stop();
                skillAnimation.Play(animName);
            }
           
            battleSkillCamera1.Follow = focus;
            battleSkillCamera1.LookAt = focus;

            StartSkillRestrict(focus.position);
        }

        private void StartSkillRestrict(Vector3 position)
        {
            if (rpgSkillRestrictObject == null)
            {
                rpgSkillRestrictObject = new GameObject("RpgSkillRestrictObject");
                rpgSkillRestrictObject.transform.SetParent(cameraFocusToken.transform);
                rpgSkillRestrictObject.layer = PveUtils.pveCameraColliderLayer;
                var collider = rpgSkillRestrictObject.AddComponent<BoxCollider>();
                collider.size = new Vector3(25,25,15);
                collider.center = new Vector3(0,0,-12);
                var confiner = battleSkillCamera1.GetComponent<CinemachineConfiner>();
                if (confiner)
                {
                    confiner.m_BoundingVolume = collider;
                }
            }
            rpgSkillRestrictObject.SetActive(true);
            rpgSkillRestrictObject.transform.position = position;
        }

        private void EndSkillRestrict()
        {
            if (rpgSkillRestrictObject)
            {
                rpgSkillRestrictObject.SetActive(false);
            }
        }
        
        
        private GameObject rpgSkillRestrictObject;

        public void ChangeRpgCameraPostProcess(bool enable)
        {
            if (uacdRpg)
            {
                uacdRpg.renderPostProcessing = enable;
            }
        }

        public void ChangeDepthTextureEnabled(bool enable)
        {
            if (uacdRpg)
            {
                uacdRpg.requiresDepthOption = enable ? CameraOnOffOption.On : CameraOnOffOption.Off;
            }
        }
        
        public void SkillStart(CinemachineBlendDefinition.Style style, float time)
        {
            rpgBrain.m_DefaultBlend.m_Style = style;
            rpgBrain.m_DefaultBlend.m_Time = time;
            SwitchCamera(EPveCameraType.battleSkill1);
        }

        public void SkillEnd(CinemachineBlendDefinition.Style style, float time)
        {
            rpgBrain.m_DefaultBlend.m_Style = style;
            rpgBrain.m_DefaultBlend.m_Time = time;
            SwitchCamera(defaultRpgCameraType);
            //EndSkillRestrict();
        }
        
        
        public void Dispose()
        {

            GameObject.DestroyImmediate(mainCamera.gameObject);
            mainCamera = null;
            GameObject.DestroyImmediate(cameraFocusToken);
            cameraFocusToken = null;
           
            if (this.loader != null)
            {
                this.loader.Recycle2Cache();
                this.loader = null;
            }
            if (pveCamera != null)
            {
                GameObject.DestroyImmediate(pveCamera);
            }
            
            var handler = ResidentHandler.Inst;
            if(handler == null) return;
            handler.RemoveFunction("L_RpgManager.SetHangingCamera");
            handler.RemoveFunction("pveManager.onCameraInit");
            handler.RemoveFunction("pveManager.bindPveCamera");
            handler.RemoveFunction("pveManager.bindRpgCamera");
            
        }
    }
}
